<template>
  <el-form
    ref="userForm"
    :model="userInfo"
    label-width="120px"
    style="margin-left: 120px; margin-top: 30px"
    :rules="rules"
  >
    <el-form-item label="姓名:" prop="username">
      <el-input v-model="userInfo.username" style="width:300px" />
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input v-model="userInfo.password" type="password" style="width:300px" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="hSubmit">更新</el-button>
    </el-form-item>
  </el-form>

</template>

<script>
import { getUserDetailById, saveUserDetailById } from '@/api/user'
export default {
  data() {
    return {
      userInfo: { // 表单数据项，和后台接口一致
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: blur }],
        password: [{ required: true, message: '用户名不能为空', trigger: blur }]
      }
    }
  },
  created() {
    this.loadUserDetailById() // 调用 获取用某个用户的信息
  },
  methods: {
    async loadUserDetailById() { // 获取用某个用户的信息
      const res = await getUserDetailById(this.$route.params.id)
      //   console.log(res)
      //   const { username, password } = res.data
      this.userInfo = res.data // 将获取的数据赋值到userInfo
    },
    async doSave() { // 保存员工信息
      const res = await saveUserDetailById(this.userInfo)
      // 接口文档中有错误：这个接口要求我们传入所有的字段，如果不传入它就会置空
      console.log(res)
    },
    hSubmit() { // 点击确定
    // 兜底校验
      this.$refs.userForm.validate(valid => {
        if (valid) { // 通过表单验证
          this.doSave()
        }
      })
    }
  }
}
</script>

<style>

</style>
